//
//  M_OrderListVC.swift
//  letuofu
//
//  Created by WH-JS on 2020/1/6.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD
import MJRefresh

class M_OrderListVC: BaseViewControllerWithHeader,UITableViewDataSource,UITableViewDelegate {
    lazy var defultView : UIView = {
        let v = UIView()
        v.backgroundColor = .clear
        let img = v.drawImage(named: "dingdankong_109") { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.width.equalTo(200)
        }
        img.contentMode = .scaleAspectFit
        
        v.drawLabel(text: "订 单 空", fontSize: 19, textColor: .x333333) { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(img.snp.bottom).offset(10)
        }.textAlignment = .center
        return v
    }()
    
    var pageIndex = 1
    var pageSize = 30
    var totalSize = 2000
    var orderItems = [[String: Any?]]()
    
    var orderType = LocalStorage.getAryToZone(forKey: ZoneCode104)
    var curZoneIndex = 0
    let tabHeader : SlidingTabHeaderScrollView
    
    var tableView = UITableView(frame: CGRect.zero, style: .grouped)
    
    let likeView = M_LikeView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        onHeaderRequery()
    }
    
    init(zoneCode:ZoneCodeModel) {
        var titles = [String]()
        var index = 0
        for model in orderType ?? [] {
            if model.name == zoneCode.name {
                curZoneIndex = titles.count
            }
            if model.name == "订单取消" {
                orderType?.remove(at: index)
            }
            else if model.name == "已确认收货" {
                titles.append("已收货")
                index += 1
            }
            else {
                titles.append(model.name)
                index += 1
            }
        }
        tabHeader = SlidingTabHeaderScrollView(screenWidth:375.0, height: 43.0,titles:titles,titleSpace:70,leftSpace:10)
        super.init()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    //确认收货操作
    func signOrderAction(orderID: String, callback: @escaping () -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "orderID":orderID]
        API.request(url: .M_OrderConfirmReceipt, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                callback()
            }
            else {
                let popup = PopupSureBox(title:"获取订单失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
    
    
    //取消订单操作
    func cancelOrderAction(orderID: String, callback: @escaping () -> Void) {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "orderID":orderID]
        API.request(url: .M_CancelOrder, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                callback()
                UIViewController.topMostController()?.view.makeToast("取消订单成功", duration: 2.0, position: .center)

            }
            else {
//                let popup = PopupSureBox(title:"获取订单失败", sureText: "确定")
//                popup.show(vc: UIViewController.topMostController() ?? self)
//                popup.onSureButtonClick = {
//                    //确定执行
//                }
                UIViewController.topMostController()?.view.makeToast("取消订单失败", duration: 2.0, position: .center)

            }
        }
        
    }
    
    func getorderDetail(orderID: String, callback: @escaping ([String:Any?]) -> Void) {
                    MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "orderID":orderID]
        API.request(url: .M_GetUserOrderDetail, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                if let data = result.data?.getDictionary("data") {
                    callback(data)
                }
            }
            else {
                let popup = PopupSureBox(title:"获取订单失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
        
    }

    func getorderList(orderProcessStateCode: String, pageIndex: Int, pageSize: Int) {
//        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "orderProcessStateCode":orderProcessStateCode,
                                    "pageIndex":pageIndex,
                                    "pageSize":pageSize]
        API.request(url: .M_GetUserOrderList, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            self.tableView.mj_header.state = .idle
            self.tableView.mj_footer.state = .idle
            if pageIndex == 1 {
                self.orderItems.removeAll()
            }
            if result.success {
                if let data = result.data?.getDictionary("data") {
                    if let dl = data.getDictList("orderItems") {
                        self.orderItems.append(contentsOf: dl)
                    }
                    self.pageIndex = data.getInt("pageIndex") ?? 1
                    self.totalSize = data.getInt("totalSize") ?? 1
                }
                self.reloadData()
            }
            else {
                self.reloadData()
            }
        }
    }
    
    func reloadData() {
        tableView.reloadData()
    }
}


// MARK: UI
extension M_OrderListVC {
    func setupUI() {
        view.backgroundColor = .xF2F2F2
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        tabHeader.backgroundColor = .white
        headTitle.text = "我的订单"
        drawRightButton(imageName: "xiangqingkefu_82")
        .addTarget(self, action: #selector(_kefuButtonClick(button:)), for: .touchUpInside)
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        safeView.addSubview(tabHeader)
        tabHeader.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(43.0)
        }
        tabHeader.callSelBlock { (index) in
            self.curZoneIndex = index
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                MBProgressHUD.showOrIncrease()
                self.getRefreshFooter().state = .refreshing
                self.refreshAll()
            }
        }
        tabHeader.onTitleSelected(button: tabHeader.buttons[curZoneIndex])
        
        //添加列表
        let _ = getRefreshHeader()
        let _ = getRefreshFooter()
        safeView.insertSubview(tableView, belowSubview: headView)
        tableView.backgroundColor = UIColor.clear;
        tableView.register(M_OrderCell.self, forCellReuseIdentifier: "M_OrderCell")
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.clipsToBounds = false
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(tabHeader.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(44)
        }
    }
    

        func getRefreshHeader()->MJRefreshHeader {
    //        顶部的下拉初始化
            let header = MJRefreshNormalHeader()
            header.lastUpdatedTimeLabel.isHidden = true
            tableView.mj_header = header
            header.setTitle("下拉刷新...", for: .idle)
            header.setTitle("下拉刷新...", for: .pulling)
            header.setTitle("下拉更新中...", for: .refreshing)
            header.setTitle("完成...", for: .willRefresh)
            header.setTitle("下拉刷新...", for: .noMoreData)
            header.setRefreshingTarget(self, refreshingAction: #selector(onHeaderRequery))

    //        顶部的处理逻辑：
            return tableView.mj_header!
        }
        
        func getRefreshFooter()->MJRefreshFooter {
            if tableView.mj_footer == nil {
                //        底部初始化：
                let footer = MJRefreshAutoNormalFooter()
//                footer.isOnlyRefreshPerDrag = true
                tableView.mj_footer = footer
                footer.setTitle("", for: .idle)
                footer.setTitle("", for: .pulling)
                footer.setTitle("下拉更新中...", for: .refreshing)
                footer.setTitle("完成...", for: .willRefresh)
                footer.setTitle("", for: .noMoreData)
                footer.setRefreshingTarget(self, refreshingAction: #selector(onFooterLoadMore))
            }

    //        底部处理逻辑：
            if pageIndex * pageSize < totalSize {
                tableView.mj_footer.endRefreshing()
            }
            else {
                tableView.mj_footer.state = .noMoreData
            }
            
    //        底部数据加载
             return tableView.mj_footer!
        }
}


// MARK: event & action
extension M_OrderListVC {
    
    @objc func _kefuButtonClick(button: Button) {
        let vc = M_SimpleArticleVC()
        pushViewController(vc)
        let qidiandic = LocalStorage.getDic(forKey: QIDIAN_KEY)
        vc.loadUrl(qidiandic?.getString("id") ?? "https://url.cn/50hfdES?_type=wpa&qidian=true")

        vc.headTitle.text = "联系客服"
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func onHeaderRequery() {
        //        顶部数据重新加载
        getRefreshFooter().state = .refreshing
        refreshAll()
    }
    
    @objc func onFooterLoadMore() {
        //        底部数据重新加载更多底部处理逻辑：
        if pageIndex * pageSize < totalSize {
            let zc = self.orderType?[curZoneIndex]
            self.getorderList(orderProcessStateCode: zc?.code ?? "", pageIndex: pageIndex+1, pageSize: pageSize)
        }
        else {
            tableView.mj_footer.state = .noMoreData
        }
    }
    
    func refreshAll() {
        let zc = self.orderType?[curZoneIndex]
        self.getorderList(orderProcessStateCode: zc?.code ?? "", pageIndex: 1, pageSize: self.pageSize)
    }
    
    func getOrderStatus(code:String) -> String {
        
        switch code {
        case "104000":
            return "全部"
        case "104001":
            return "待支付"
        case "104002":
            return "待发货"
        case "104003":
            return "待收货"
        case "104004":
            return "已确认收货"
        case "104005":
            return "订单取消"

        default:
            return "无效订单"
        }
        
    }
    
    func getDeliveryMethod(code:String) -> String {
        switch code {
        case "103001":
        return "定点自提"
        case "103002":
        return "快递运输"
        default:
        return "默认配送方式"
        }
           
    }
    
    ///MARK: UITableViewDelegate
        // 选中cell后执行此方法
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//            MBProgressHUD.showOrIncrease()
            let order = orderItems[indexPath.section]
            self.getorderDetail(orderID: order.getString("orderID") ?? "", callback: { (orderDetail) in
//                MBProgressHUD.hideOrDecrease()
                let vc = M_OrderDetail()
                vc.orderDic = orderDetail
                self.pushViewController(vc)
            })
        }
        
        ///MARK: UITableViewDataSource
        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let head = UIView()
            head.backgroundColor = .white
            
            if orderItems.count == 0 {
                head.backgroundColor = .xF2F2F2
                head.drawView(view: defultView, { (make) in
                    make.left.right.top.bottom.equalToSuperview()
                })
            }
            else {
                let orderData = orderItems[section]
                 let sendLab = head.drawLabel(text: "收货方式：" + getDeliveryMethod(code: orderData.getString("deliverModeCode") ?? "未知"), fontSize: 12, textColor: .x333333) { (make) in
                     make.left.equalToSuperview().offset(10)
                     make.top.equalToSuperview().offset(20)
                 }
                 
                 head.drawLabel(text: getOrderStatus(code: orderData.getString("orderProcessStateCode") ?? ""), fontSize: 12, textColor: .xFC4C02){ (make) in
                     make.right.equalToSuperview().offset(-10)
                     make.top.equalToSuperview().offset(20)
                 }
                
                if let pc = orderData.getString("pOrderID"), pc != "0" {
                    let pLab = head.drawLabel(text: "父订单号："+pc, fontSize: 12, fontWeight: .regular, textColor: .x999999){ (make) in
                        make.left.equalToSuperview().offset(10)
                        make.top.equalTo(sendLab.snp.bottom).offset(10)
                    }
                    
                     var zoneTitle = ""
                     var img = UIImage()
                     if orderData.getString("zoneCode") == "105001"  {
                         zoneTitle = "自营专区"
                         img = UIImage.init(named: "zhiyingdianpu_33")!
                     }
                     else {
                         zoneTitle = "京东配送"
                         img = UIImage.init(named: "jdong_34")!
                     }
                     
                    let titlelab = head.drawLabel(text: zoneTitle, fontSize: 12, textColor: .x333333) { (make) in
                         make.left.equalToSuperview().offset(33)
                         make.top.equalTo(pLab.snp.bottom).offset(10)
                     }
                     head.drawImage(image: img) { (make) in
                         make.left.equalToSuperview().offset(10)
                         make.centerY.equalTo(titlelab)
                     }
                }
                else {
                     var zoneTitle = ""
                     var img = UIImage()
                     if orderData.getString("zoneCode") == "105001"  {
                         zoneTitle = "自营专区"
                         img = UIImage.init(named: "zhiyingdianpu_33")!
                     }
                     else {
                         zoneTitle = "京东配送"
                         img = UIImage.init(named: "jdong_34")!
                     }
                     
                    let titlelab = head.drawLabel(text: zoneTitle, fontSize: 12, textColor: .x333333) { (make) in
                         make.left.equalToSuperview().offset(33)
                         make.top.equalTo(sendLab.snp.bottom).offset(20)
                     }
                     head.drawImage(image: img) { (make) in
                         make.left.equalToSuperview().offset(10)
                         make.centerY.equalTo(titlelab)
                     }
                }
                 
            }
            return head
        }
        
        //头部高度
        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            if orderItems.count == 0 {
                return 300
            }
           return 85
        }
        
        //组数
        func numberOfSections(in tableView: UITableView) -> Int {
            if orderItems.count == 0 {
                return 1
            }
            return orderItems.count
        }
        
        //尾部高度
        func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
            if orderItems.count == 0 {
                //                let rownum = 5
                var rownum = Double(self.likeView.productListArr.count)/2
                rownum = ceil(rownum)
                return CGFloat((251+7)*rownum-7+52)
            }
            var footHeight:CGFloat = 0.0
            if orderItems.count > 0 {
                let order = orderItems[section]
                //待支付
                if order.getString("orderProcessStateCode") == "104001"  {
                    footHeight = 200 - 34 + 21
                }
                    //待发货
                else if order.getString("orderProcessStateCode") == "104002" {
                    //20201013： 待发货状态好像注释掉了取消订单按钮
                    footHeight = 173 - 34 + 1 //200 - 34 + 21
                }
                    //待收货
                else if order.getString("orderProcessStateCode") == "104003" {
                    footHeight = 200 - 34 + 21
                }
                    //订单取消
                else if order.getString("orderProcessStateCode") == "104005" {
                    footHeight = 173 - 34 + 1
                }
                    //已确认收货
                else if order.getString("orderProcessStateCode") == "104004" {
                    footHeight = 200 - 34 + 21
                }
            }
            if section+1 == orderItems.count,pageIndex * pageSize >= totalSize {
                tableView.mj_footer.state = .noMoreData
//                let rownum = 5
                var rownum = Double(self.likeView.productListArr.count)/2
                rownum = ceil(rownum)
                footHeight += CGFloat((251+7)*rownum-7+52)
                return footHeight
            }
            else {
                return footHeight
            }
        }
    
    //尾部view
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if orderItems.count == 0 {
            let footView = UIView()
            footView.backgroundColor = .white
            
            likeView.removeFromSuperview()
            footView.drawView(view: likeView) {(make) in
                make.top.equalToSuperview()
                make.left.right.bottom.equalToSuperview()
            }
            
            if likeView.productListArr.count == 0 {
                likeView.getDataList(zoneCode: "105001", pageIndex: 1, pageSize: 10, callback: { (conut) in
                    if conut > 0 {
                        self.reloadData()
                    }
                })
                likeView.callselBlock { (info) in
                    let vc = M_ProductDetailVC(info: info)
                    self.pushViewController(vc)
                }
            }
            
            return footView
        }
        let footView = M_OrderListFootView()
        let order = orderItems[section]
        footView.orderData = order
        
        footView.callPayBlock(block: { (data) in
//            MBProgressHUD.showOrIncrease()
            self.getorderDetail(orderID: data.getString("orderID") ?? "", callback: { (orderDetail) in
//                MBProgressHUD.hideOrDecrease()
                let vc = M_PayVC(orderDetail,price: footView.priceLab.text)
                self.pushViewController(vc)
            })
        })
        
        footView.callSignBlock(block: { (data) in
            self.signOrderAction(orderID: data.getString("orderID") ?? "", callback: {
                self.refreshAll()
            })
        })
        
        footView.callSeeBlock(block: { (data) in
            let vc = M_LogisticsVC(orderid: data.getString("orderID") ?? "")
            self.pushViewController(vc)
        })
        
        footView.callCancelBlock(block: { (data) in
            let popup = PopupConfirmBox(info: "是否取消订单？", title: "")
            popup.show(vc: UIViewController.topMostController() ?? self)
            popup.onSureButtonClick = {
                //确定执行
                self.cancelOrderAction(orderID: data.getString("orderID") ?? "", callback: {
                    self.refreshAll()
                })
            }
        })

        if section+1 == orderItems.count,pageIndex * pageSize >= totalSize {
            likeView.removeFromSuperview()
            var footHeight = 200 - 34 + 21
            if order.getString("orderProcessStateCode") == "104005"
                || order.getString("orderProcessStateCode") == "104002"{
                footHeight = 173 - 34 + 1
            }
            footView.drawView(view: likeView) {(make) in
                make.top.equalTo(footHeight)
                make.left.right.bottom.equalToSuperview()
            }
            
            if likeView.productListArr.count == 0 {
                likeView.getDataList(zoneCode: "105001", pageIndex: 1, pageSize: 10, callback: { (conut) in
                    if conut > 0 {
                        self.reloadData()
                    }
                })
                likeView.callselBlock { (info) in
                    let vc = M_ProductDetailVC(info: info)
                    self.pushViewController(vc)
                }
            }
        }
        
        return footView
    }
    
    // 设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120
    }
    
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if orderItems.count == 0 {
            return 0
        }
        let items = orderItems[section].getDictList("items")
        return items?.count ?? 0
    }
    
    // UITableViewCell
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cellid = "M_OrderCell"
            let items = orderItems[indexPath.section]
            let item = items.getDictList("items")
            var cell = tableView.dequeueReusableCell(withIdentifier: cellid) as? M_OrderCell
            if cell==nil {
                cell = M_OrderCell(style: .subtitle, reuseIdentifier: cellid)
            }
            
            cell?.zoonCode = items.getString("zoneCode")
            cell?.unitLab.text = items.getString("centUnitName")
            cell?.celldata = item?[indexPath.row]
            return cell!
    }
}
